using System.Windows.Controls;
using System.Collections.Generic;
using System;
using System.Reflection;

namespace ibba.src.noriskbo
{
    public static class ListBoxExtensions
    {
        /// <summary>
        /// Augments ListBox.SelectedIndex to work around a bug where setting
        /// SelectedIndex before the ListBox is visible does not update the UI.
        /// </summary>
        /// <remarks>
        /// Instead of:
        ///     listBox.SelectedIndex = 1;
        /// Use:
        ///     listBox.SelectedIndex = 1;
        ///     listBox.SelectedIndexWorkaround();
        /// </remarks>
        /// <param name="listBox">Extension method class.</param>
        public static void SelectedIndexWorkaround(this ListBox listBox)
        {
            int selectedIndex = listBox.SelectedIndex;
            bool set = false;
            listBox.LayoutUpdated += delegate
            {
                if (!set)
                {
                    // Toggle value to force the change
                    listBox.SelectedIndex = -1;
                    if (listBox.Items.Count > 0)
                        listBox.SelectedIndex = selectedIndex;
                    set = true;
                }
            };
        }
        /// <summary>
        /// Augments ListBoxItem.IsSelected to work around a bug where setting
        /// IsSelected before the ListBoxItem is visible does not update the UI.
        /// </summary>
        /// <remarks>
        /// Instead of:
        ///     listBoxItem.IsSelected = true;
        /// Use:
        ///     listBoxItem.IsSelected = true;
        ///     listBoxItem.IsSelectedWorkaround();
        /// </remarks>
        /// <param name="listBoxItem">Extension method class.</param>
        public static void IsSelectedWorkaround(this ListBoxItem listBoxItem)
        {
            bool isSelected = listBoxItem.IsSelected;
            bool set = false;
            listBoxItem.LayoutUpdated += delegate
            {
                if (!set)
                {
                    // Toggle value to force the change
                    listBoxItem.IsSelected = !isSelected;
                    listBoxItem.IsSelected = isSelected;
                    set = true;
                }
            };
        }

        public static int RemoveAll<T>(this IList<T> list, Predicate<T> predicate) 
        { 
            int returnCount = 0; 
            
            for (int i = list.Count - 1; i >= 0; --i) 
            { 
                if (predicate(list[i])) 
                { 
                    list.RemoveAt(i); returnCount++; 
                } 
            } 
            
            return returnCount; 
        }
    }
}
